package com.dkm.dkmproject.utils.WechatGongutils;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class WebUtilsone {

    public static Map getMwebUrl(String url,String xmlParam){
        String jsonStr = null;
        HttpClient httpClient = new HttpClient();
        Map map = new HashMap();
        try {
            PostMethod method = null;
            RequestEntity reqEntity = new StringRequestEntity(xmlParam,"text/json","UTF-8");
            method = new PostMethod(url);
            method.setRequestEntity(reqEntity);
            method.addRequestHeader("Content-Type","application/json;charset=utf-8");
            httpClient.executeMethod(method);
            StringBuffer resBodyBuf = new StringBuffer();
            byte[] responseBody = new byte[1024];
            int readCount = 0;
            BufferedInputStream is = new BufferedInputStream(method.getResponseBodyAsStream());
            while((readCount = is.read(responseBody,0,responseBody.length))!=-1){
                resBodyBuf.append(new String(responseBody,0,readCount,"utf-8"));
            }
            jsonStr = resBodyBuf.toString();
            System.out.println(jsonStr);
            map = XMLUtils.parseXmlToList(jsonStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
    public static String getHttpData(String url, String data) throws Exception{
        StringBuffer resultData = new StringBuffer();
        URL postUrl = new URL(url);// url到？
        HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
        osw.write(data); // data是url问号之后的所有参数集合
        osw.flush();
        osw.close();
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
        resultData.append(line);
        }
        reader.close();
        return resultData.toString();
    }

}

